package com.practice.algorithm.consistentHash;

import com.practice.dataStructure.list.ArrayList;
import com.practice.dataStructure.list.List;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Node {
    // 每个节点对应200个虚拟节点
    private static final int VIRTUAL_NODE_NO_PER_NODE = 200;

    private final String ip;

    // 修改为存储 long 类型的哈希值
    private final List<Long> virtualNodeHashes = new ArrayList<>(VIRTUAL_NODE_NO_PER_NODE);

    private final Map<Object, Object> cacheMap = new HashMap<>();

    public Node(String ip) {
        Objects.requireNonNull(ip);
        this.ip = ip;
        initVirtualNodes();
    }

    // 初始化虚拟节点
    private void initVirtualNodes() {
        String virtualNodeKey;
        for (int i = 0; i < VIRTUAL_NODE_NO_PER_NODE; i++) {
            virtualNodeKey = ip + "#VN" + i;
            virtualNodeHashes.add(HashUtils.hashcode(virtualNodeKey));
        }
    }

    public void addCacheItem(Object key, Object value) {
        cacheMap.put(key, value);
    }

    public Object getCacheItem(Object key) {
        return cacheMap.get(key);
    }

    public void removeCacheItem(Object key) {
        cacheMap.remove(key);
    }

    public List<Long> getVirtualNodeHashes() {
        return virtualNodeHashes;
    }

    public String getIp() {
        return ip;
    }

    @Override
    public String toString() {
        return "Node{" +
                "ip='" + ip + '\'' +
                ", virtualNodeHashes=" + virtualNodeHashes.size() +
                ", cacheMap=" + cacheMap.size() +
                '}';
    }
}
